<script lang="ts" setup>
import { Message } from '@arco-design/web-vue'
import { Workbook } from 'exceljs'
import { useDebounceFn } from '@vueuse/core'
import ClassStatus from './components/ClassStatus.vue'
import { ClassInfoApi, ClassroomApi } from '@/apis'
import type { TableInstanceColumns } from '@/components/ProTable/type'
import { useTable } from '@/hooks/modules/useTable'
import { useDictFilterOptions, useForm } from '@/hooks'
import { generateHeaders, saveWorkbook } from '@/utils/excel'
import { useUserStore } from '@/stores'

defineOptions({
  name: 'TeacherClassList',
})

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const { form, resetForm } = useForm<ClassInfoApi.ClassQuery>({
  keyword: undefined,
  subject: undefined,
  classYear: new Date().getFullYear().toString(),
  classCategory: undefined,
  campusId: undefined,
  classroomId: undefined,
  term: undefined,
  grade: undefined,
  classTypeId: undefined,
  leadTeacherId: userStore.userInfo.id,
  classStatus: undefined,
  saleStatus: undefined,
})

watch(() => route.query, () => {
  Object.assign(form, route.query)
}, {
  immediate: true,
})

// 更多筛选
const filterCollapsed = ref<boolean>(true)

const {
  tableData,
  loading,
  pagination,
  search,
} = useTable(pagination => ClassInfoApi.getClassPage({ ...form, ...pagination }))

const columns: TableInstanceColumns[] = [
  {
    title: '班级',
    dataIndex: 'name',
    slotName: 'name',
    fixed: 'left',
    width: 350,
  },
  { title: '年份科目', dataIndex: 'classYear', slotName: 'classYear', width: 150 },
  { title: '校区教室', dataIndex: 'classroomId', slotName: 'classroom', minWidth: 150, ellipsis: true, tooltip: true },
  { title: '招生进度', dataIndex: 'enrollProgress', slotName: 'enrollProgress', width: 200 },
  { title: '上课进度', dataIndex: 'classProgress', slotName: 'classProgress', width: 240 },
  { title: '班级状态', dataIndex: 'classStatus', slotName: 'classStatus', minWidth: 120, filterable: {
    filters: useDictFilterOptions('ClassStatusEnum'),
    multiple: true,
  } },
  { title: '总价', dataIndex: 'totalPrice', slotName: 'totalPrice', minWidth: 120 },
  { title: '上架状态', dataIndex: 'saleStatus', slotName: 'saleStatus', minWidth: 120, filterable: {
    filters: useDictFilterOptions('SaleStatusEnum'),
    multiple: false,
  } },
]

// 详情
const onDetail = (row) => {
  router.push({ path: '/education/class/detail', query: { id: row.id } })
}

// 筛选
const onFilterChange = (dataIndex, filteredValues) => {
  form[dataIndex] = filteredValues
}

const refresh = () => {
  resetForm()
  search()
}

const changeStatus = async (record) => {
  await ClassInfoApi.updateSaleStatus({ classId: record.id, status: record.saleStatus })
  Message.success('修改成功')
  search()
}

const debouncedSearch = useDebounceFn(() => {
  search()
}, 100)

watch(() => form, () => {
  debouncedSearch()
}, { deep: true })

const allClassroomList = ref<any[]>([])
const classroomList = ref<any[]>([])

const getAllClassroomList = (query: any) => {
  loading.value = true
  ClassroomApi.getList(query).then((res) => {
    allClassroomList.value = res
  }).finally(() => {
    loading.value = false
  })
}

watch(() => form.campusId, (newId, oldId) => {
  if (newId !== oldId && newId !== undefined && newId !== '') {
    console.log('newId = ', newId, 'oldId = ', oldId)
    classroomList.value = allClassroomList.value.filter(item => item.campusId === newId)
    console.log('classroom = ', classroomList.value)
  } else {
    classroomList.value = []
  }
})

onMounted(() => {
  getAllClassroomList({})
})

const onExportExcel = () => {
  // 创建工作簿
  const workbook = new Workbook()
  // 添加sheet
  const worksheet = workbook.addWorksheet('班级信息')
  // 设置 sheet 的默认行高
  worksheet.properties.defaultRowHeight = 20
  // 设置列
  const column = columns
  column.splice(-1, 1)
  worksheet.columns = generateHeaders(column)
  // 添加行
  const data = tableData.value.map((item) => {
    return {
      ...item,
      name: item.name,
      classYear: item.classYear,
      classroomId: item.classroomId,
      enrollProgress: item.enrollStudentCount / item.planStudentCount,
      classProgress: item.completedLessonCount / item.totalLessonCount,
    }
  })
  worksheet.addRows(data)
  // 导出excel
  saveWorkbook(workbook, '班级信息.xlsx')
}
</script>

<template>
  <ProPage title="我的班级" description="管理我的班级信息">
    <!-- <template #title-right>
      <Statistics />
    </template> -->
    <ProTable :data="tableData" :columns="columns" :loading="loading" :pagination="pagination" @refresh="refresh" @filter-change="onFilterChange">
      <template #search-panel>
        <a-space direction="vertical" size="medium">
          <a-space>
            <label class="label">关键词</label>
            <a-input-search
              v-model="form.keyword"
              class="!min-w-360px"
              placeholder="班级名称关键词"
              search-button
              allow-clear
              @press-enter="search"
            />
            <CollapseButton v-model="filterCollapsed" />
          </a-space>
          <a-space v-show="filterCollapsed" direction="vertical" size="medium">
            <a-space>
              <label class="label">学期年级</label>
              <a-year-picker v-model="form.classYear" placeholder="年份" class="!w-150px" />
              <DictSelect v-model="form.term" type="button" code="TermEnum" placeholder="学期" />
              <DictSelect v-model="form.grade" type="select" code="Grade" placeholder="年级" class="!w-120px" />
              <DictSelect v-model="form.subject" type="select" code="Subject" placeholder="科目" class="!w-120px" />
            </a-space>

            <a-space>
              <label class="label">其他条件</label>
              <DictSelect v-model="form.classCategory" type="button" code="ClassCategoryEnum" placeholder="类型" />
              <ClassTypeSelect v-model="form.classTypeId" placeholder="班型" class="!min-w-150px" />
              <CampusSelect v-model="form.campusId" placeholder="校区" class="!min-w-150px" />
              <a-select v-if="form.campusId !== undefined" v-model="form.classroomId" placeholder="教室" allow-clear :allow-search="{ retainInputValue: true }" class="!min-w-150px">
                <a-option v-for="item in classroomList" :key="item.id" :value="item.id" :label="item.name" />
              </a-select>
              <ClassroomSelect v-else v-model="form.classroomId" placeholder="教室" class="!min-w-200px" />
            </a-space>
          </a-space>
        </a-space>
      </template>

      <template #toolbar-right>
        <a-button v-permission="['edu:class:read']" type="primary" @click="onExportExcel">
          <template #icon>
            <icon-download />
          </template>
          <span>导出</span>
        </a-button>
      </template>

      <template #name="{ record }">
        <CellClassInfo :id="record.id" :name="record.name" :lead-teacher-name="record.leadTeacherName" :assist-teacher-name="record.assistTeacherName" />
      </template>
      <template #classYear="{ record }">
        <DictLabel v-model="record.grade" code="Grade" /> · <DictLabel v-model="record.subject" code="Subject" />
        <div class="text-13px text-gray-4">
          {{ record.classYear }}年 · <DictLabel v-model="record.term" code="TermEnum" />
        </div>
      </template>
      <template #classroom="{ record }">
        <div>{{ record.classroomName || '-' }}</div>
        <div class="text-13px text-gray-4">
          {{ record.campusName }}
        </div>
      </template>
      <template #enrollProgress="{ record }">
        <div>
          <a-progress :percent="record.planStudentCount === 0 ? 0 : record.enrollStudentCount / record.planStudentCount " :show-text="true" :steps="record.planStudentCount" size="small">
            <template #text>
              {{ record.enrollStudentCount || 0 }}/{{ record.planStudentCount || 0 }}
            </template>
          </a-progress>
          <div class="mt-1 flex flex-justify-between font-size-[13px]">
            <a-tag v-if="record.pendingPayCount" size="small" color="red">
              {{ record.pendingPayCount }}人未支付
            </a-tag>
          </div>
        </div>
      </template>
      <template #totalPrice="{ record }">
        <span class="text-orange">￥{{ record.totalPrice || 0 }}</span>
      </template>
      <template #classProgress="{ record }">
        <div>
          <a-progress :percent="!record.totalLessonCount ? 0 : record.completedLessonCount / record.totalLessonCount " :stroke-width="6">
            <template #text>
              {{ record.completedLessonCount || 0 }}/{{ record.totalLessonCount || 0 }}
            </template>
          </a-progress>
          <span class="mt-1 text-13px text-gray-4">{{ record.lessonStartDate }} ~ {{ record.lessonEndDate }}</span>
        </div>
      </template>
      <template #classStatus="{ record }">
        <ClassStatus code="ClassStatusEnum" :status="record.classStatus" />
      </template>
      <template #saleStatus="{ record }">
        <a-switch v-model="record.saleStatus" type="round" :checked-value="1" :unchecked-value="0" @change="changeStatus(record)" />
      </template>
    </ProTable>
  </ProPage>
</template>

<style lang="less" scoped>
.class-card {
  margin-top: 10px;
}
.label {
  display: inline-block;
  width: 60px;
  text-align: right;
  flex-shrink: 0;
  margin-right: 10px;
  color: var(--color-text-1);
}
</style>
